package com.scy.edu.handler;

import com.scy.edu.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 司晨雨
 * @date 2020/8/20 22:31
 * @description
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext ;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        String className = request.getClassName();
        Object[] parameters = request.getParameters();
        String methodName = request.getMethodName();
        Class<?>[] parameterTypes = request.getParameterTypes();

        Class<?> aClass = Class.forName(className);
        Object bean = applicationContext.getBean(aClass);
        Method method = bean.getClass().getMethod(methodName, parameterTypes);
        Object obj = method.invoke(bean, parameters);
        ctx.writeAndFlush(obj);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServiceHandler.applicationContext = applicationContext;
    }
}
